#ifndef __LOG_HPP__
#define __LOG_HPP__

#include <cstddef>
#include<cstdio>
#include"Mutex.hpp"
#include <filesystem>//  c++17
#include <fstream>
#include<string>
#include<unistd.h>

namespace LogModule
{
    using namespace MutexModule;

    const std::string gesp = "\r\n";

    class LogStrategy
    {
    public:
        ~LogStrategy() = default; //显式指定析构函数为默认实现
        virtual void SyncLog(const std::string &message) = 0;
    };

    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy()
        {
        }

        void SyncLog(const std::string & message) override
        {
            LockGuard lockguard(_mutex);//隐式类型转换  构造函数无参数直接构造
            std::cout<<message<<gesp;
        }
        ~ConsoleLogStrategy()
        {
        }
    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./log";
    const std::string defaultfile = "my.log";

    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &file = defaultfile)
        : _path(path),
          _file(file)
        {
            LockGuard lockguard(_mutex);
            if(std::filesystem::exists(_path)) // 文件是否存在
            {
                return ;
            }
            try    //  try  catch  捕捉异常  
            {
                std::filesystem::create_directories(_path);
            } 
            catch (const std::filesystem::filesystem_error &e) 
            {   
                std::cout << e.what() << '\n';
            }
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);

            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file; 
            std::ofstream out(filename, std::ios::app);// 追加写的方式打开
            if(!out.is_open())
            {
                return ;
            }
            out << message << gesp;  //  输入到文件中  
            out.close();
        }

        ~FileLogStrategy()
        {

        }
    private:
        std::string _path;//日志所在路径
        std::string _file;//日志所在文件
        Mutex _mutex;
    };

    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string Level2Str(LogLevel level)  // 日志等级
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    std::string GetTimeStamp() //  获取当前时间
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer),"%4d-%02d-%02d %02d:%02d:%02d",
            curr_tm.tm_year+1900,
            curr_tm.tm_mon+1,
            curr_tm.tm_mday,
            curr_tm.tm_hour,
            curr_tm.tm_min,
            curr_tm.tm_sec
        );
        return timebuffer;
    }

    // 形成日志
    class Logger
    {
    public:
        Logger()
        {
            EnableConsolLogStrategy();
        }
        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        void EnableConsolLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }

        class LogMessage
        {
        public:
            LogMessage(LogLevel& level, std::string& src_name, int line_number, Logger& logger)
            :   _curr_time(GetTimeStamp()),
                _level(level),
                _pid(getpid()),
                _src_name(src_name),
                _line_number(line_number),
                _logger(logger)
            {
                //  日志左边连续起来 
                std::stringstream ss;
                ss << "[" << _curr_time << "] "
                   << "[" << Level2Str(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _src_name << "] "
                   << "[" << _line_number << "] "
                   << "- ";
                _loginfo = ss.str();
            }

            template<typename T>
            //  对于错误的日志详细信息  反复循环<<输入进入——loginfo  最后在析构的时候打印出来
            LogMessage &operator<<(const T &info)// <<操作符重载
            {
                std::stringstream ss;
                ss<<info;
                _loginfo += ss.str();
                return *this;
            }
            //  函数析构时直接把日志按照策略输出
            ~LogMessage()
            {
                if(_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _src_name;
            int _line_number;
            Logger &_logger;
            std::string _loginfo;//日志输出的string
        };
        //  巧妙的重载 与 返回 ！！！！
        LogMessage operator()(LogLevel level, std::string name, int line)
        {
            return LogMessage(level, name, line, *this);
        }
        ~Logger()
        {

        }
    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };
    Logger logger;
#define LOG(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.EnableConsolLogStrategy()
#define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()
}

#endif